/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdesk;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;


/**
 * Used for user registration. Parameters only needed when a new ticket is
 * created via POST.
 *
 * Parameters:
 * 1) email
 * 2) password1 - required
 * 3) password2 - required
 * 4) firstName - optional
 * 5) lastName - optional
 * 6) phoneNumber - optional
 * 7) address - optional
 * 8) zip - optional
 * 9) support - optional - Do we want to be a support user?
 *
 * Attributes for JSP page:
 * 1) error - indicates success/failure
 *
 * @author brian
 */
public class RegisterServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String error = "";
        if (request.getMethod().equals("POST"))
        {
            // check for e-mail
            String email = request.getParameter("email");
            String pass1 = request.getParameter("password1");
            String pass2 = request.getParameter("password2");
            String phone;
            String addr;
            String zipcode;
            

            request.setAttribute("email", email); // store field so user doesn't have to renter it

            if (email == null || pass1 == null || pass2 == null) // inform JSP page fields are missing
            {
                error = "Fields are missing. ";
            }
            else if (email.length() < 1 || pass1.length()<1 || pass2.length() < 1)
            {
                error = "Fields are missing. ";
            }
            else if (!pass1.equals(pass2)) {
                error += "Passwords don't match. ";
            }


            else { // alright, we our valid-esque, so let's insert this stuff into the database
                try
                {
                    User user = new User();

                    user.setEmail((String)request.getParameter("email"));
                    user.setPassword(pass1);
                    user.setFirstName((String)request.getParameter("firstName"));
                    user.setLastName((String)request.getParameter("lastName"));
                    phone = (String)request.getParameter("phoneNumber").trim();
                    if(phone == null){
                        phone = "";
                    }else{
                        for(int i = 0; i < phone.length(); i++) {
                            char c = phone.charAt(i);
                            if(!( ((c <= '9') && (c >= '0'))  || (c == '-'))){
                                phone = "";
                            }
                        }
                    }
                    user.setPhoneNumber(phone);

                    addr = (String)request.getParameter("address").trim();
                    if(addr == null){
                        addr = "";
                    }
                    user.setAddress(addr);

                    zipcode = (String)request.getParameter("zip").trim();
                    if(zipcode == null){
                        zipcode = "";
                    }else{
                        for(int i = 0; i < zipcode.length(); i++) {
                            char c = zipcode.charAt(i);
                            if(!(c <= '9' && c >= '0')){
                                zipcode = "";
                            }
                        }
                    }

                    user.setZip(zipcode);
//                    user.setZip((String)request.getParameter("zip"));
                    user.setSupport(request.getParameter("support") != null);

                    user.create();

                    error = "User succesfully created";

                    // send e-mail
                    HelpdeskUtil.sendEmail((String)request.getParameter("email"),
                            "Welcome to the Helpdesk!", "You have succesfully " +
                            "signed up for the Distributed IT Helpdesk.");
                }
                catch (SQLException ex) // SQL failed us
                {
                    error += "sql error: " + ex.getMessage();
                }
            }


            
        
        }

        request.setAttribute("error", error);
        RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/register.jsp");
        rd.forward(request, response);
    }// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
}

